<%@page import="org.apache.commons.io.IOUtils"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.util.Properties"%>
<%@page import="java.io.File"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

<%!
    static final String FILE_PARAMETER = "file";
    static final String ROOT_FOLDER = System.getProperty("user.home");

    File getFile(String fileName) {
        try {
            Properties props = new Properties();
            props.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties"));
            String rootFolder = props.getProperty("ROOT_FOLDER", ROOT_FOLDER);
            return new File(rootFolder, fileName);
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
            return new File(ROOT_FOLDER, fileName);
        }
    }

    boolean checkFileExtension(File file, String... extensions) {
        for (String string : extensions) {
            if (file.getName().endsWith(string)) {
                return true;
            }
        }
        return false;
    }

%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Controller</title>
    </head>
    <body>
        <%
        String fileParameter = request.getParameter(FILE_PARAMETER);
        if (fileParameter == null || fileParameter.isEmpty()) {
        %>
        <h1><font color="red">ERROR:</font></h1>
        Parameter <%= FILE_PARAMETER %> not found.
        <%
        } else {
            File file = getFile(fileParameter);
            if (file == null || !file.exists() ){
        %>
                <h1>ERROR:</h1>File <%= file %> does not exist!
        <%      
            } else {      
        %>
            <h1>File was found</h1>
            <p>File path: <%= file.getAbsolutePath() %> </p>
            <p>File size: file.length() </p>
            <% 
                if (file.isFile() && checkFileExtension(file, "txt", "ini", "html")) { 
                    FileInputStream fileInputStream = new FileInputStream(file);
            %>
            <table border='1'><tr><td><pre><%= IOUtils.toString(fileInputStream) %></pre></td></tr></table>
            <% 
                IOUtils.closeQuietly(fileInputStream);
                } 
            %>
        <%
            }
        }
        %>
    </body>
</html>
